<?php

namespace Biz\service\wiki;

use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiRankingHot;
use Biz\service\Album\AlbumListService;
use Biz\service\Album\FormatAlbumService;
use Biz\service\brand\Brand;
use Biz\service\ShopClassify;
use Biz\service\Store\StoreBasicService;
use Biz\service\wikiRanking\Ranking;
use Doraemon\model\Blank as mBlank;
use Doraemon\service\Format\Blank\HandleBlank;
use Doraemon\service\Format\Note\HandleNote;
use Doraemon\service\Guide;
use Doraemon\service\statSign\Basic as basicStatSign;
use Doraemon\tools\BlockType;


class RecommendCardFormater
{
    const MIDDLEWARE_H5_URL = "/shop/wiki-middle-page";
    private $active_uid = '';
    private $card_list = [];
    private $formated_card_list = [];

    private $photo_ids = [];
    private $guide_ids = [];
    private $blank_ids = [];
    private $wiki_ids = [];
    private $brand_ids = [];
    private $category_ids = [];
    private $ranking_ids = [];
    private $category_to_ranking_id = [];
    private $store_ids = [];
    private $album_ids = [];//好物清单id集合


    private $photo_list = [];
    private $guide_list = [];
    private $blank_list = [];
    private $brand_list = [];
    private $wiki_list = [];
    private $category_list = [];
    private $ranking_list = [];

    private $store_list = [];
    private $album_list = [];

    public function __construct($card_list, $active_uid = 0)
    {
        $this->card_list = $card_list;
        $this->active_uid = $active_uid;
    }

    public function getFormatedList()
    {
        $this->parse();
        foreach ($this->card_list as $card) {
            switch ($card['obj_type']) {
                case BlockType::TYPE_ANSWER:
                case BlockType::TYPE_PHOTO:
                    array_push($this->formated_card_list, $this->FormatPhoto($card));
                    break;
                case BlockType::TYPE_GUIDE:
                    array_push($this->formated_card_list, $this->FormatGuide($card));
                    break;
                case BlockType::TYPE_SITEM:
                    array_push($this->formated_card_list, $this->FormatItem($card));
                    break;
                case BlockType::TYPE_BLANK:
                    array_push($this->formated_card_list, $this->FormatBlank($card));
                    break;
                case BlockType::TYPE_BRAND:
                    array_push($this->formated_card_list, $this->FormatBrand($card));
                    break;
                case BlockType::TYPE_WIKI:
                    array_push($this->formated_card_list, $this->FormatWiki($card));
                    break;
                case BlockType::TYPE_CATEGORY_WIKI:
                    array_push($this->formated_card_list, $this->FormatCategory($card));
                    break;
                case BlockType::TYPE_BANNER://banner
                    array_push($this->formated_card_list, $this->FormatBanner($card));
                    break;
                case BlockType::TYPE_CAROUSEL_BANNER://轮播
                    array_push($this->formated_card_list, $this->FormatBannerCarousel($card));
                    break;
                case BlockType::TYPE_STORE://门店
                    array_push($this->formated_card_list, $this->FormateStore($card));
                    break;
                case BlockType::TYPE_WIKI_ALBUM://好物清单
                    array_push($this->formated_card_list, $this->FormateAlbum($card));
                    break;
                default:
                    break;
            }
        }
        $this->formated_card_list = array_filter($this->formated_card_list);
        $this->formated_card_list = array_values($this->formated_card_list);
        return $this->formated_card_list;
    }

    private function parse()
    {
        $this->extractId();
        $this->extractPhotoList();
        $this->extractGuideList();
        $this->extractBlankList();
        $this->extractBrandList();
        $this->extractWikiList();
        $this->extractCategoryList();
        $this->extractStoreList();
        $this->extractAlbumList();
    }

    private function extractId()
    {
        foreach ($this->card_list as $item) {
            switch ($item['obj_type']) {
                case BlockType::TYPE_ANSWER:
                case BlockType::TYPE_PHOTO:
                    array_push($this->photo_ids, $item['obj_id']);
                    break;
                case BlockType::TYPE_GUIDE:
                case BlockType::TYPE_SITEM:
                    array_push($this->guide_ids, $item['obj_id']);
                    break;
                case BlockType::TYPE_BLANK:
                    array_push($this->blank_ids, $item['obj_id']);
                    break;
                case BlockType::TYPE_BRAND:
                    array_push($this->brand_ids, $item['obj_id']);
                    break;
                case BlockType::TYPE_WIKI:
                    array_push($this->wiki_ids, $item['obj_id']);
                    break;
                case BlockType::TYPE_CATEGORY_WIKI:
                    array_push($this->category_ids, $item['obj_id']);
                    break;
                case BlockType::TYPE_STORE:
                    array_push($this->store_ids, $item['obj_id']);
                    break;
                case BlockType::TYPE_WIKI_ALBUM:
                    array_push($this->album_ids, $item['obj_id']);
                    break;
                default:
                    break;
            }
        }
    }

    private function extractPhotoList()
    {
        $this->photo_ids = array_filter($this->photo_ids);
        if ($this->photo_ids && is_array($this->photo_ids)) {
            //$this->photo_list = Photos::getPhotosForDynamic($this->photo_ids, $this->active_uid);
            $this->photo_list = HandleNote::handleNote($this->photo_ids, HandleNote::WIKI_MASONRY_LAYOUTS, $this->active_uid);
        }
    }

    private function extractGuideList()
    {
        if ($this->guide_ids && is_array($this->guide_ids)) {
            $this->guide_list = Guide::getGuidesForRecommend3_2($this->guide_ids, $this->active_uid, ['wiki' => true]);
        }
    }

    private function extractBlankList()
    {
        if ($this->blank_ids && is_array($this->blank_ids)) {
            //$this->blank_list = Blank::getBlanksForDynamic($this->blank_ids, $this->active_uid, ['wiki' => true]);
            $this->blank_list = HandleBlank::handleBlank($this->blank_ids, HandleBlank::WIKI_MASONRY_LAYOUTS, $this->active_uid);
        }
    }

    private function extractBrandList()
    {
        if ($this->brand_ids && is_array($this->brand_ids)) {
            $this->brand_list = Brand::multiFormatBrandCard($this->brand_ids);
        }
    }

    private function extractWikiList()
    {
        if ($this->wiki_ids && is_array($this->wiki_ids)) {
            $this->wiki_list = Wiki::getWikiList($this->wiki_ids, $this->active_uid, Wiki::FIELDS_GROUP_MASONRY_LIST);
        }
    }

    private function extractStoreList()
    {
        if ($this->store_ids && is_array($this->store_ids)) {
            $this->store_list = StoreBasicService::getStoreCardByStroreIds($this->store_ids, $this->active_uid);
        }
    }

    private function extractAlbumList()
    {
        if ($this->album_ids && is_array($this->album_ids)) {
            $albumInfos = AlbumListService::getAlbumListByAlbumIds($this->album_ids, FormatAlbumService::WIKI_FEED_LIST);
            if ($albumInfos) {
                foreach ($albumInfos as $info) {
                    $this->album_list[$info['album_info']['album_id']] = $info['album_info'];
                }
            }
        }
    }

    private function extractCategoryList()
    {
        if ($this->category_ids && is_array($this->category_ids)) {
            $categoryTypeList = $this->getCategoryType();
            $rankingIds = [];
            $categoryIds = [];
            //查询分类是否有榜单，有榜单，则返回榜单信息
            foreach ($categoryTypeList as $classifyId => $row) {
                if ($row['obj_type'] == BlockType::TYPE_RANKING) {
                    $rankingIds[] = $row['obj_id'];
                    $this->category_to_ranking_id[$classifyId] = $row['obj_id'];
                } else {
                    $categoryIds[] = $row['obj_id'];
                }
            }
            $this->category_ids = $categoryIds;
            $this->ranking_ids = $rankingIds;

            if ($this->category_ids && is_array($this->category_ids)) {
                $this->category_list = ClassifyList::formateMultiCategoryIds($this->category_ids);
            }
            if ($this->ranking_ids && is_array($this->ranking_ids)) {
                $this->ranking_list = Ranking::multiFormatRankingCard($this->ranking_ids);
            }
        }
    }


    private function FormatPhoto($card)
    {
        $data = [];
        if (isset($this->photo_list[$card['obj_id']])) {
            $data = $this->photo_list[$card['obj_id']];
            $data['photo']['wiki_info']['style'] = Wiki::WIKI_STYLE_GOOD_THING;
            if ($data['photo']['wiki_info']['list'] && is_array($data['photo']['wiki_info']['list'])) {
                $data['photo']['wiki_info']['list'] = \Doraemon\tools\StatSign::versionCompatible($data['photo']['wiki_info']['list'], \Doraemon\tools\StatSign::WIKI_UP_GRADE_VERSION_522, BlockType::TYPE_WIKI, 'wiki');
            } else {
                return [];
            }
            $params = [
                'recommend_reason' => $card['recommend_reason'],
                'relevant_tag' => $card['relevant_tag'],
            ];
            $data['statSign'] = self::getStatSign($card['obj_id'], BlockType::TYPE_PHOTO, $params);
        }
        return $data;
    }

    private function FormatGuide($card)
    {
        $data = [];
        if (isset($this->guide_list[$card['obj_id']])) {
            $data['type'] = BlockType::TYPE_GUIDE;
            $data['guide'] = $this->guide_list[$card['obj_id']];
            $data['guide']['wiki_info']['style'] = Wiki::WIKI_STYLE_GOOD_THING;
            if ($data['guide']['wiki_info']['list'] && is_array($data['guide']['wiki_info']['list'])) {
                $data['guide']['wiki_info']['list'] = \Doraemon\tools\StatSign::versionCompatible($data['guide']['wiki_info']['list'], \Doraemon\tools\StatSign::WIKI_UP_GRADE_VERSION_522, BlockType::TYPE_WIKI, 'wiki');
            } else {
                return [];
            }
            $params = [
                'recommend_reason' => $card['recommend_reason'],
                'relevant_tag' => $card['relevant_tag'],
            ];
            $data['statSign'] = self::getStatSign($card['obj_id'], BlockType::TYPE_GUIDE, $params);
        }
        return $data;
    }

    private function FormatItem($card)
    {
        $data = [];
        if (isset($this->guide_list[$card['obj_id']])) {
            $data['type'] = BlockType::TYPE_SITEM;
            $data['guide'] = $this->guide_list[$card['obj_id']];
            $data['guide']['wiki_info']['style'] = Wiki::WIKI_STYLE_GOOD_THING;
            if ($data['guide']['wiki_info']['list'] && is_array($data['guide']['wiki_info']['list'])) {
                $data['guide']['wiki_info']['list'] = \Doraemon\tools\StatSign::versionCompatible($data['guide']['wiki_info']['list'], \Doraemon\tools\StatSign::WIKI_UP_GRADE_VERSION_522, BlockType::TYPE_WIKI, 'wiki');
            } else {
                return [];
            }
            $params = [
                'recommend_reason' => $card['recommend_reason'],
                'relevant_tag' => $card['relevant_tag'],
            ];
            $data['statSign'] = self::getStatSign($card['obj_id'], BlockType::TYPE_SITEM, $params);
        }
        return $data;
    }


    private function FormatBlank($card)
    {
        $data = [];
        if (isset($this->blank_list[$card['obj_id']])) {
            $data = $this->blank_list[$card['obj_id']];
            $data['blank']['wiki_info']['style'] = Wiki::WIKI_STYLE_GOOD_THING;
            if ($data['blank']['wiki_info']['list'] && is_array($data['guide']['wiki_info']['list'])) {
                $data['blank']['wiki_info']['list'] = \Doraemon\tools\StatSign::versionCompatible($data['blank']['wiki_info']['list'], \Doraemon\tools\StatSign::WIKI_UP_GRADE_VERSION_522, BlockType::TYPE_WIKI, 'wiki');
            } else {
                return [];
            }
            $params = [
                'recommend_reason' => $card['recommend_reason'],
                'relevant_tag' => $card['relevant_tag'],
            ];
            $data['statSign'] = self::getStatSign($card['obj_id'], BlockType::TYPE_BLANK, $params);
            if ((isset($data['blank']['blank_info']['status']) && $data['blank']['blank_info']['status'] == mBlank::STATUS_WAIT_CHECK)) {
                unset($this->blank_list[$card['obj_id']]);
                return;
            }
        }
        return $data;
    }

    private function FormatBrand($card)
    {
        $data = [];
        if (isset($this->brand_list[$card['obj_id']])) {
            $data['type'] = BlockType::TYPE_BRAND;
            $data['brand']['user_info'] = $this->brand_list[$card['obj_id']]['user_info'];
            $data['brand']['resume_info'] = $this->brand_list[$card['obj_id']]['resume_info'];
            $params = [
                'recommend_reason' => $card['recommend_reason'],
                'relevant_tag' => $card['relevant_tag'],
            ];
            $data['statSign'] = self::getStatSign($card['obj_id'], BlockType::TYPE_BRAND, $params);
        }
        return $data;
    }

    private function FormatCategory($card)
    {
        $data = [];
        $rankingId = (isset($this->category_to_ranking_id[$card['obj_id']]) && $this->category_to_ranking_id[$card['obj_id']]) ? $this->category_to_ranking_id[$card['obj_id']] : false;
        if ($rankingId && isset($this->ranking_list[$rankingId]) && $this->ranking_list[$rankingId]) {
            $rankingId = $this->category_to_ranking_id[$card['obj_id']];
            $data['type'] = BlockType::TYPE_RANKING;
            $data['ranking']['ranking_info'] = $this->ranking_list[$rankingId];
            $params = [
                'recommend_reason' => $card['recommend_reason'],
                'relevant_tag' => $card['relevant_tag'],
            ];
            $data['statSign'] = self::getStatSign($rankingId, BlockType::TYPE_RANKING, $params);
        } else if (isset($this->category_list[$card['obj_id']])) {
            $data['type'] = BlockType::TYPE_CATEGORY_WIKI;
            $data['wiki_category'] = $this->category_list[$card['obj_id']];
            $params = [
                'recommend_reason' => $card['recommend_reason'],
                'relevant_tag' => $card['relevant_tag'],
            ];
            $data['statSign'] = self::getStatSign($card['obj_id'], BlockType::TYPE_CATEGORY_WIKI, $params);
        }
        return $data;
    }

    private function FormatWiki($card)
    {
        $data = [];
        if (isset($this->wiki_list[$card['obj_id']]) && !in_array($this->wiki_list[$card['obj_id']]['channel'], [mWiki::CHANNEL_XIAOEPINPIN, mWiki::CHANNEL_AMAZON, mWiki::CHANNEL_XIAOMIYOUPIN,])) {
            $data['type'] = BlockType::TYPE_WIKI;
            $data['wiki'] = $this->wiki_list[$card['obj_id']];
            $data['wiki']['middle_link'] = WikiMiddle::getMiddleLink($this->wiki_list[$card['obj_id']]);

            $params = [
                'recommend_reason' => $card['recommend_reason'],
                'relevant_tag' => $card['relevant_tag'],
            ];

            $data['statSign'] = self::getStatSign($card['obj_id'], BlockType::TYPE_WIKI, $params);
        }
        return $data;
    }

    private function FormatBanner($card)
    {
        $data = $card['card_info'];
        return $data;
    }

    private function FormatBannerCarousel($card)
    {
        $bannerList = [];
        foreach ($card['card_info'] as $key => $row) {
            $bannerList[] = $row;
        }
        $data = [
            'type' => BlockType::TYPE_CAROUSEL_BANNER,
            'banner_list' => $bannerList
        ];
        return $data;
    }


    private function FormateStore($card)
    {
        $data = [];
        if (isset($this->store_list[$card['obj_id']])) {
            $data['type'] = BlockType::TYPE_STORE;
            $data['store']['store_info'] = $this->store_list[$card['obj_id']];
            $data['statSign'] = self::getStatSign($card['obj_id'], BlockType::TYPE_STORE);
        }
        return $data;
    }

    private function FormateAlbum($card)
    {
        $data = [];
        if (isset($this->album_list[$card['obj_id']])) {
            $data['type'] = BlockType::TYPE_WIKI_ALBUM;
            $data['album_info'] = $this->album_list[$card['obj_id']] ?? [];
            $data['statSign'] = self::getStatSign($card['obj_id'], BlockType::TYPE_WIKI_ALBUM);
        }
        return $data;
    }

    /**
     * 前台分类，查询是否有榜单，有榜单返回榜单，否则返回前台分类
     * @return array
     */
    public function getCategoryType()
    {
        $result = [];
        if ($this->category_ids && is_array($this->category_ids)) {
            $classifyIds = $this->category_ids;
            $result = [];
            $day = Ranking::getRankingDay();
            $classifyRankingIds = ShopClassify::mGetClassifyRankingIds($classifyIds);
            foreach ($classifyIds as $classifyId) {
                $rankingIds = isset($classifyRankingIds[$classifyId]) ? $classifyRankingIds[$classifyId] : [];
                if ($rankingIds) {
                    $showRankingIds = WikiRankingHot::selectByWhere([
                        'ranking_id' => $rankingIds,
                        'ranking_day' => $day,
                        'ranking_state' => WikiRankingHot::RANKING_STATE_SHOW,
                        'ORDER' => ['score' => 'DESC'],
                    ], 'ranking_id');
                    $rankingId = $showRankingIds ? array_rand($showRankingIds) : 0;
                    if ($rankingId) {
                        $result[$classifyId] = ['obj_id' => $rankingId, 'obj_type' => BlockType::TYPE_RANKING];
                    }
                } else {
                    $result[$classifyId] = ['obj_id' => $classifyId, 'obj_type' => BlockType::TYPE_CATEGORY_WIKI];
                }
            }
        }
        return $result;
    }

    private static function getStatSign($objId, $objType, array $params = [], $index = null)
    {
        $extend[basicStatSign::EXTEND_KEY_OBJ_ID] = $objId;
        $extend[basicStatSign::EXTEND_KEY_OBJ_TYPE] = $objType;
        if (!is_null($index)) {
            $extend[basicStatSign::EXTEND_KEY_INDEX] = $index;
        }
        return basicStatSign::genStatSign(basicStatSign::MODULE_FINE_GOODS_FEED_CARD, $extend, $params);
    }
}